// projects/oa/pages/sample/edit/sample_edit.js
// 导入路径辅助模块，避免重复引用
const pathImport = require('../helpers/path_import.js');
const { pageHelper, cloudHelper, validate } = pathImport;;
const { createStoreBindings } = require('mobx-miniprogram-bindings');
const { sampleStore } = require('../../../config/store_config.js');

// 调试模式开关
const DEBUG_MODE = true;

// 调试数据
const DEBUG_DATA = {
	// 权限数据
	permissionData: {
		SAMPLE_EDIT: true,  // 样品编辑权限
		SAMPLE_VIEW: true,  // 样品查看权限
		SAMPLE_DELETE: true // 样品删除权限
	},
	// 样品阶段选项
	statusOptions: [
		{ label: '调试中', value: 1 },
		{ label: '试产中', value: 2 },
		{ label: '大货中', value: 3 }
	],
	// 项目选项
	projectOptions: [
		{ label: '项目A', value: 'proj_001' },
		{ label: '项目B', value: 'proj_002' },
		{ label: '项目C', value: 'proj_003' }
	],
	// 样品详情
	sampleDetail: {
		_id: 'debug_1',
		SAMPLE_CODE: 'DBG001',
		SAMPLE_NAME: '调试样品1',
		SAMPLE_VERSION: 'V1.0',
		SAMPLE_CUSTOMER: '测试客户',
		SAMPLE_PROJECT_ID: 'proj_001',
		SAMPLE_STATUS: 1,
		SAMPLE_LOCATION: '测试位置',
		SAMPLE_MAKE_USER_ID: 'user_001',
		SAMPLE_NOTES: '这是一个测试样品',
		SAMPLE_ATTACHMENTS: []
	}
};

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		// 仅保留UI配置相关的本地状态
		isLoad: false,
		id: ''
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		ProjectBiz.initPage(this);
		
		if (!options || !options.id) {
			pageHelper.showModal('参数错误');
			wx.navigateBack();
			return;
		}

		this.setData({
			id: options.id
		});
		
		// 创建MobX绑定
		this.storeBindings = createStoreBindings(this, {
			store: sampleStore,
			fields: [
				'formData',
				'options',
				'loading',
				'canAdd'
			],
			actions: [
				'resetFormData',
				'setFormField', 
				'setStatusIndex',
				'setProjectIndex',
				'loadOptions',
				'addAttachments',
				'removeAttachment',
				'loadEditData',
				'submitSampleEdit',
				'checkAddPermission'
			]
		});

		// 加载选项数据
		await this.loadOptions();
		
		// 加载编辑数据
		const result = await this.loadEditData(options.id);
		
		if (result && result.success) {
			this.setData({
				isLoad: true
			});
		} else {
			pageHelper.showModal('加载数据失败');
			setTimeout(() => {
				wx.navigateBack();
			}, 1500);
		}
		
		// 检查权限
		await this.checkAddPermission();
	},
	
	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {
		// 销毁绑定
		if (this.storeBindings) {
			this.storeBindings.destroyStoreBindings();
		}
	},

	/**
	 * 状态选择
	 */
	bindStatusChange: function(e) {
		let index = Number(e.detail.value);
		if (index >= 0 && index < this.data.options.statusOptions.length) {
			this.setStatusIndex(index);
		}
	},

	/**
	 * 项目选择
	 */
	bindProjectChange: function(e) {
		let index = Number(e.detail.value);
		this.setProjectIndex(index);
	},

	/**
	 * 表单输入
	 */
	bindInput: function(e) {
		let field = e.currentTarget.dataset.field;
		let value = e.detail.value;
		this.setFormField(field, value);
	},

	/**
	 * 选择图片
	 */
	bindChooseImageTap: async function() {
		try {
			let res = await wx.chooseMedia({
				count: 9,
				mediaType: ['image'],
				sizeType: ['compressed']
			});

			wx.showLoading({
				title: '上传中...',
				mask: true
			});

			await this.addAttachments(res.tempFiles);
			
			wx.hideLoading();
		} catch (err) {
			console.error('选择或上传图片失败:', err);
			wx.hideLoading();
			pageHelper.showModal('选择图片失败，请重试');
		}
	},

	/**
	 * 删除图片
	 */
	bindDelImageTap: function(e) {
		let index = e.currentTarget.dataset.index;
		this.removeAttachment(index);
	},

	/**
	 * 预览图片
	 */
	previewImage: function(e) {
		let url = e.currentTarget.dataset.url;
		if (!url) return;

		let urls = this.data.formData.SAMPLE_ATTACHMENTS;
		wx.previewImage({
			current: url,
			urls
		});
	},

	/**
	 * 取消
	 */
	bindCancelTap: function() {
		wx.navigateBack();
	},

	/**
	 * 表单提交
	 */
	bindFormSubmit: async function () {
		try {
			// 表单验证
			const rules = [
				{ fields: ['formData.SAMPLE_CODE'], name: '存样编号', required: true },
				{ fields: ['formData.SAMPLE_NAME'], name: '样品名称', required: true },
			];
			
			// 进行表单验证
			const checkRes = pageHelper.formVerify(this.data, rules);
			if (!checkRes) return;
			
			const callback = async () => {
				try {
					const result = await this.submitSampleEdit(this.data.id);
					
					if (result) {
						pageHelper.showSuccessToast('编辑成功', 1500);
						setTimeout(() => {
							wx.navigateBack();
						}, 1500);
					}
				} catch (err) {
					console.error(err);
					pageHelper.showModal('编辑失败，请重试');
				}
			};
			
			pageHelper.showConfirm('确认提交?', callback);
		} catch (err) {
			console.error(err);
		}
	}
});